package co.fitstart.mobile.web.controller.credit.mall;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.entity.credit.Credit;
import co.fitstart.entity.credit.product.CreditProduct;
import co.fitstart.entity.credit.product.CreditProductTag;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.UserAddress;
import co.fitstart.mobile.service.CreditMallService;
import co.fitstart.mobile.service.CreditProductService;
import co.fitstart.mobile.service.CreditService;
import co.fitstart.mobile.service.UserAddressService;
import co.fitstart.mobile.web.interceptor.MobileDetect;
import co.fitstart.mobile.web.interceptor.Router;
import co.fitstart.mobile.web.interceptor.WechatAuthority;
import co.fitstart.mobile.web.resolver.Secure;

/**
 * 
 * @author houtao
 *
 */
@Controller
@RequestMapping("/credit-mall")
public class CreditMallController {

    private static final Logger logger = LoggerFactory.getLogger(CreditMallController.class);

    @Autowired
    private CreditMallService creditMallService;

    @Autowired
    private CreditProductService creditProductService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private CreditService creditService;

    /**
     * 积分商城主页
     * 
     * @return
     */
    @WechatAuthority
    @MobileDetect
    @Router(targetUrl = "/required-wechat")
    @RequestMapping("")
    public ModelAndView index(@Secure User user) {
        ModelAndView modelAndView = new ModelAndView("credit/mall/credit-mall-index");

        List<CreditProduct> creditProducts = creditMallService.listCreditProduction(CreditProductTag.CREDITPRESENT);

        Credit credit = creditService.generallyLoad(user);

        modelAndView.addObject("credit", credit);

        modelAndView.addObject("creditProducts", creditProducts);

        return modelAndView;
    }

    @RequestMapping(value = "/products")
    public ModelAndView list(HttpServletRequest request, CreditProductTag tag, Page page) {

        if (tag == null) {
            return new ModelAndView("redirect:products?tag=CREDITPRESENT");
        }
        ModelAndView modelAndView = new ModelAndView("credit/mall/credit-mall-list");

        List<CreditProduct> creditProducts = creditProductService.list(tag, page);

        modelAndView.addObject("creditProducts", creditProducts);

        modelAndView.addObject("creditProductsSize", creditProducts.size());

        modelAndView.addObject("tag", tag);

        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));

        return modelAndView;
    }

    /**
     * 商品列表
     * 
     * @param tag
     * @param page
     * @return
     */
    @RequestMapping(value = "/products", params = "filter", method = RequestMethod.GET)
    public ModelAndView listProducts(HttpServletRequest request,
            @RequestParam(defaultValue = "CREDITPRESENT") CreditProductTag tag, Page page) {
        ModelAndView modelAndView = new ModelAndView("fragment/credit/mall/credit-product-list-fragment");

        List<CreditProduct> creditProducts = creditMallService.listCreditProduction(tag, page);

        modelAndView.addObject("creditProducts", creditProducts);

        modelAndView.addObject("page", page);

        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));

        return modelAndView;
    }

    /**
     * 商品详情
     * 
     * @param productId
     * @return
     */
    @WechatAuthority
    @MobileDetect
    @Router(targetUrl = "/required-wechat")
    @RequestMapping("/products/{productId}")
    public ModelAndView view(@Secure User user, @PathVariable("productId") Long productId,
            @RequestParam(name = "userAddressId", required = false) Long userAddressId) {

        ModelAndView modelAndView = new ModelAndView("credit/mall/credit-mall-view");

        CreditProduct creditProduct = creditProductService.load(CreditProduct.class, productId);

        UserAddress userAddress = null;

        if (userAddressId != null) {

            userAddress = userAddressService.load(userAddressId);
        } else {
            userAddress = userAddressService.loadUserDefaultAddress(user);
        }
        int maxExchangeNum = creditMallService.calculateMaxExchangeNum(creditProduct, user);

        modelAndView.addObject("cp", creditProduct);

        modelAndView.addObject("userAddress", userAddress);

        modelAndView.addObject("maxExchangeNum", maxExchangeNum);

        return modelAndView;
    }

    @WechatAuthority
    @MobileDetect
    @Router(targetUrl = "/required-wechat")
    @RequestMapping(path = "/products/{productId}/addresses", method = RequestMethod.GET)
    public ModelAndView listAddresses(@Secure User user, @PathVariable("productId") Long productId) {

        ModelAndView modelAndView = new ModelAndView("profile/address/profile-address-list");

        List<UserAddress> userAddresses = userAddressService.listUserAddress(user);

        UserAddress defaultAddress = userAddressService.loadUserDefaultAddress(user);

        modelAndView.addObject("defaultAddressId", defaultAddress);

        modelAndView.addObject("userAddresses", userAddresses);

        modelAndView.addObject("addressType", "product");

        modelAndView.addObject("productId", productId);

        return modelAndView;
    }

    @WechatAuthority
    @MobileDetect
    @Router(targetUrl = "/required-wechat")
    @RequestMapping(path = "/products/{creditProductId}/addresses/create")
    public ModelAndView addAddress(@PathVariable("creditProductId") Long creditProductId) {

        ModelAndView modelAndView = new ModelAndView("profile/address/profile-address-create");

        modelAndView.addObject("addressType", "product");

        modelAndView.addObject("creditProductId", creditProductId);

        return modelAndView;
    }

    @WechatAuthority
    @MobileDetect
    @Router(targetUrl = "/required-wechat")
    @RequestMapping(path = "/products/{productId}/addresses", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody String onAddAddress(@Secure User user, @PathVariable("productId") Long productId,
            UserAddress address, String defaultAddress) {

        Result result = new Result();

        if (defaultAddress != null && defaultAddress.equals("on")) {
            address.makeDefault();
        }

        Integer id = userAddressService.create(user, address);

        result.success().data("productId", productId);

        result.data("addressType", "product");

        /*
         * result.data("selected", selected);
         */
        result.data("addressId", id);

        return JsonUtils.toJsonString(result);
    }

    /**
     * edit profileAddress.
     * 
     * @param user
     * @param id
     * @return
     */
    @WechatAuthority
    @MobileDetect
    @RequestMapping(value = "/products/{productId}/addresses/{addressId}/edit", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    public ModelAndView edit(@Secure User user, @PathVariable("addressId") Long addressId,
            @PathVariable("productId") Long productId) {

        ModelAndView modelAndView = new ModelAndView("profile/address/profile-address-edit");

        UserAddress userAddress = userAddressService.load(addressId);

        modelAndView.addObject("userAddress", userAddress);

        modelAndView.addObject("addressType", "product");

        modelAndView.addObject("creditProductId", productId);

        return modelAndView;
    }

    @WechatAuthority
    @MobileDetect
    @Router(targetUrl = "/required-wechat")
    @RequestMapping(path = "/products/{productId}/addresses/{addressId}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody String onEditAddress(@Preloading("id") UserAddress address, String defaultAddress,
            @PathVariable("productId") Long productId, @Secure User user) {

        Result result = new Result();

        if (defaultAddress != null && defaultAddress.equals("on")) {
            address.makeDefault();
        }
        try {

            userAddressService.edit(user, address);

            result.success().message("更新地址成功");

        } catch (Exception e) {

            result.fail().message(e.getMessage());

            logger.error("CreditMallController#oneEditAddress() error:", e);
        }

        return JsonUtils.toJsonString(result);
    }

}
